package com.flycms.esmodule.utils;

import org.apache.commons.lang.math.NumberUtils;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author huangzt
 * @version 1.0
 * @date 2020/3/15 19:33
 */
public class EsUtils {

    /**
     * 反射设置字段高亮
     * @param fieldName
     * @return
     */
    private static String parSetName(String fieldName) {
        if (null == fieldName || "".equals(fieldName)) {
            return null;
        }
        int startIndex = 0;
        if (fieldName.charAt(0) == '_'){
            startIndex = 1;
        }
        return "set" + fieldName.substring(startIndex, startIndex + 1).toUpperCase()
                + fieldName.substring(startIndex + 1);
    }

    /**
     * 设置高亮
     * @param hit 命中记录
     * @param filed 字段
     * @param object 待赋值对象
     */
    public static void setHighLight(SearchHit hit, String filed, Object object){
        //获取对应的高亮域
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        HighlightField highlightField = highlightFields.get(filed);
        if (highlightField != null){
            //取得定义的高亮标签
            String highLightMessage = highlightField.fragments()[0].toString();
            // 反射调用set方法将高亮内容设置进去
            try {
                String setMethodName = parSetName(filed);
                Class<?> Clazz = object.getClass();
                Method setMethod = Clazz.getMethod(setMethodName, String.class);
                setMethod.invoke(object, highLightMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将 yyyy-MM-dd'T'HH:mm:ss.SSS Z 转换成 Date
     */
    public static Date formateDate(String dateStr){
        SimpleDateFormat format;
        try {
            if (dateStr.endsWith("Z")){
                dateStr = dateStr.replace("Z", " UTC");
                format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
                return format.parse(dateStr);
            } else if(NumberUtils.isNumber(dateStr)){
                return new Date(Long.parseLong(dateStr));
            } else {
                format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return format.parse(dateStr);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
